package com.coffee.wx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coffee.wx.entity.business.WxUser;
import com.coffee.wx.service.IWxUserInfoService;
import com.coffee.wx.service.IWxUserService;
import com.coffee.wx.uitls.SendHttpUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class WxUserInfoServiceImpl implements IWxUserInfoService {

    private final String APPID = "wx1679fc8e56c3f821";

    private final String APPSECRET = "ee6f4b9af98d70cee1b7a72a15af5117";

    // 通过code换取网页授权access_token
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    // 通过网页授权access_token获取用户信息
    private static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";

    @Resource
    private IWxUserService wxUserService;

    @Override
    public String getUserInfo(String code, String state) {

        // 获取用户accessToken
        Map<String, Object> userAccessTokenMap = this.getUserAccessTokenByCode(code, state);
        String errcode = MapUtil.getStr(userAccessTokenMap, "errcode", null);
        if (errcode != null) {
            Console.log("获取用户accessToken失败" + userAccessTokenMap);
        }
        String openid = MapUtil.getStr(userAccessTokenMap, "openid", null);
        String accessToken = MapUtil.getStr(userAccessTokenMap, "access_token", null);

        // 获取用户信息
        Map<String, Object> userInfoMap = this.getUserInfoByAccessToken(accessToken, openid);
        errcode = MapUtil.getStr(userInfoMap, "errcode", null);
        if (errcode != null) {
            Console.log("获取用户信息失败" + userInfoMap);
        }

        // 保存用户信息
        WxUser wxUser = BeanUtil.fillBeanWithMap(userInfoMap, new WxUser(), true);
        wxUser.setNickName(MapUtil.getStr(userInfoMap, "nickname", null))
                .setAvatar(MapUtil.getStr(userInfoMap, "headimgurl", null))
                .setUnionId(MapUtil.getStr(userInfoMap, "unionid", null))
                .setOpenId(MapUtil.getStr(userInfoMap, "openid", null));
        boolean saveOrUpdate = wxUserService.saveOrUpdate(wxUser,
                Wrappers.<WxUser>lambdaUpdate().eq(WxUser::getOpenId, openid));

        String msg;
        if (saveOrUpdate) {
            msg = """
                    <h1>报名成功</h1>
                    返回公众号输入：<h5>海报</h5> 分享活动，邀请好友助力
                    返回公众号输入：<h5>排行版</h5> 查看助力排行榜
                    """;
        } else {
            msg = """
                    <h1>报名失败</h1>
                    请稍后重试
                    若多次报名失败，请联系管理员处理
                    """;
        }
        return msg;
    }

    @Override
    public Map<String, Object> getUserAccessTokenByCode(String code, String state) {
        String response = SendHttpUtils.doGet(
                String.format(GET_ACCESS_TOKEN_URL, APPID, APPSECRET, code),
                null);
        return JSONUtil.parse(response).toBean(Map.class);
    }

    @Override
    public Map<String, Object> getUserInfoByAccessToken(String accessToken, String openId) {
        String response = SendHttpUtils.doGet(
                String.format(GET_USER_INFO_URL, accessToken, openId),
                null);
        return JSONUtil.parse(response).toBean(Map.class);
    }


}
